package com.lly.pro.filter;
import com.lly.pro.common.ResponseJsonUtil;
import com.lly.pro.common.ResponseStatusCodes;
import com.xiaoleilu.hutool.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 过滤未登录请求
 * @author Hommond
 * @date 2/22/2019
 */
@Component
@WebFilter(filterName = "test", urlPatterns = "/*")
public class AuthFilter implements Filter {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    private static final String ACCESS_URI = "/login";
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.info("AuthFilter init___________________________________");

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        //uri不是/login且session中没有保存userId信息的话返回未登录状态码，不允许访问
        if (!ACCESS_URI.equals(request.getRequestURI()) && request.getSession().getAttribute("userId") == null ){
            OutputStream out = servletResponse.getOutputStream();
            JSONObject json = new JSONObject(ResponseJsonUtil.getErrorResult(ResponseStatusCodes.NOT_LOGGED_IN,"用户未登录"));
            out.write(json.toString().getBytes());
        }
        //已登录状态可以继续访问
        else{
            filterChain.doFilter(servletRequest,servletResponse);
        }
    }

    @Override
    public void destroy() {
        logger.info("AuthFilter destroy________________________________");

    }
}
